package com.example.ems.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(urlPatterns = {"/index.jsp", "/DepartmentServlet", "/EmployeeServlet", "/SalaryServlet", "*.jsp"})
public class AuthFilter implements Filter {
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        HttpSession session = request.getSession(false);

        String requestURI = request.getRequestURI();
        String contextPath = request.getContextPath();

        // Allow access to login page, auth servlet, and static resources (CSS)
        if (requestURI.equals(contextPath + "/login.jsp") ||
                requestURI.equals(contextPath + "/AuthServlet") ||
                requestURI.startsWith(contextPath + "/css/")) {
            chain.doFilter(request, response);
            return;
        }

        if (session == null || session.getAttribute("loggedInUser") == null) {
            response.sendRedirect(contextPath + "/login.jsp");
        } else {
            chain.doFilter(request, response);
        }
    }
    public void init(FilterConfig filterConfig) {}
    public void destroy() {}
}
